'use strict';
const opentracing = require('@alicloud/opentracing');
const tracer = new opentracing.Tracer('fabric-egg');

module.exports = (options, app) => {
    return async function traceMiddleware(ctx, next) {
        // log receive request
        ctx.tracer = tracer
        var req = ctx.req
        req.parentSpan = tracer.startSpan('root');
        req.parentSpan.setTag(opentracing.Tags.PEER_HOSTNAME, req.hostname);
        req.parentSpan.setTag(opentracing.Tags.HTTP_METHOD, req.method.toUpperCase());
        req.parentSpan.setTag(opentracing.Tags.HTTP_URL, req.url);
        try {
            await next();
        } catch (e) {
           throw e
        } finally {
            var req = ctx.req
            req.parentSpan.setTag(opentracing.Tags.HTTP_STATUS_CODE, ctx.response.status);
            req.parentSpan.finish(req);
        }
    }
};